<template>
  <a-card>
    <div :class="advanced ? 'search' : null">
      <a-form layout="horizontal">
        <div :class="advanced ? null : 'fold'">
          <a-row>
            <a-col :md="8" :sm="24">
              <a-form-item
                label="宠物名称"
                :labelCol="{ span: 5 }"
                :wrapperCol="{ span: 14, offset: 1 }"
              >
                <a-input v-model="searchName" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item
                label="宠物品种"
                :labelCol="{ span: 5 }"
                :wrapperCol="{ span: 14, offset: 1 }"
              >
                <a-select placeholder="请选择" v-model="searchBreed">
                  <a-select-option
                    v-for="i in petBreedList"
                    :key="i.value"
                    :value="i.value"
                    >{{ i.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item
                label="宠物年龄"
                :labelCol="{ span: 5 }"
                :wrapperCol="{ span: 14, offset: 1 }"
              >
                <a-input-number
                  v-model="searchAge"
                  style="width: 100% !important"
                  :min="1"
                  placeholder="月"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item
                label="体重"
                :labelCol="{ span: 5 }"
                :wrapperCol="{ span: 14, offset: 1 }"
              >
                <a-input-number
                  v-model="searchWeight"
                  placeholder="KG"
                  style="width: 100% !important"
                  :min="1"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <span style="float: right; margin-top: 3px">
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button style="margin-left: 8px" @click="handleReset"
            >重置</a-button
          >
          <a @click="toggleAdvanced" style="margin-left: 8px">
            {{ advanced ? "收起" : "展开" }}
            <a-icon :type="advanced ? 'up' : 'down'" />
          </a>
        </span>
      </a-form>
    </div>
    <div>
      <a-space class="operator">
        <a-button @click="addNew" type="primary">新增宠物</a-button>
        <!-- <a-button>批量操作</a-button>
        <a-dropdown>
          <a-menu slot="overlay">
            <a-menu-item key="delete">删除</a-menu-item>
            <a-menu-item key="audit">审批</a-menu-item>
          </a-menu>
          <a-button> 更多操作 <a-icon type="down" /> </a-button>
        </a-dropdown> -->
      </a-space>
      <standard-table
        bordered
        :columns="columns"
        :dataSource="isSearch ? searchList : petList"
        :rowKey="(record) => record.id"
        @change="onChange"
      >
        <div slot="description" slot-scope="{ text }">
          {{ text }}
        </div>
        <div slot="action" slot-scope="{ id, record }">
          <a style="margin-right: 8px" @click="handleDeed">
            <a-icon type="eye" />喂食</a
          >
          <a style="margin-right: 8px" @click="handleVaccinate">
            <a-icon type="eye" />疫苗</a
          >
          <a style="margin-right: 8px" @click="handleEdit(record)">
            <a-icon type="edit" />编辑
          </a>
          <Popconfirm
            title="确定删除该项？"
            ok-text="确定"
            cancel-text="取消"
            @confirm.stop="deleteRecord(id)"
          >
            <a style="margin-right: 8px" class="text_red">
              <a-icon type="delete" />删除
            </a>
          </Popconfirm>
          <a @click="handleVaccinate"> <a-icon type="eye" />详情</a>
        </div>
        <template slot="statusTitle">
          <a-icon @click.native="onStatusTitleClick" type="info-circle" />
        </template>
      </standard-table>
    </div>
    <Modal
      title="管理宠物"
      maskClosable
      :confirm-loading="confirmLoading"
      :visible="openModal"
      :width="700"
      @ok="handleOk"
      @cancel="openModal = false"
    >
      <petForm
        :form="petFromData"
        :petBreedList="petBreedList"
        @setPetFromData="setPetFromData"
      />
    </Modal>
  </a-card>
</template>

<script>
import StandardTable from "@/components/table/StandardTable";
import { findIndex, map } from "lodash";

const petBreedList =
  map(
    JSON.parse(localStorage.getItem("petBreedList"))?.slice(1),
    ({ breedName }, index) => ({
      value: 1 + index,
      name: breedName,
    })
  ) || [];
const columns = [
  {
    title: "宠物名称",
    dataIndex: "petName",
    align: "center",
  },
  {
    title: "宠物品种",
    dataIndex: "petBreed",
    align: "center",
    customRender: (text) => petBreedList[text - 1]?.name,
  },
  {
    title: "宠物年龄",
    dataIndex: "petAge",
    align: "center",
    customRender: (text) => text + "月",
  },
  {
    title: "宠物体重",
    dataIndex: "petWeight",
    align: "center",
    customRender: (text) => text + "kg",
  },
  {
    title: "最近喂食时间",
    dataIndex: "",
    align: "center",
  },
  {
    title: "最近疫苗时间",
    dataIndex: "",
    align: "center",
  },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
    align: "center",
    width: 310,
  },
];
import petForm from "./Modules/petForm.vue";
import { v4 as uuidv4 } from "uuid";
import { Modal, message, Popconfirm } from "ant-design-vue";
import { sleep } from "../../utils/util";
export default {
  name: "QueryList",
  components: { StandardTable, Modal, Popconfirm, petForm },
  data() {
    return {
      advanced: true,
      columns,
      petList: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      petFromData: {
        petName: "",
        petBreed: "",
        petAge: "",
        petWeight: "",
      },
      confirmLoading: false,
      openModal: false,
      petBreedList,

      isSearch: false,
      searchList: [],
      searchName: "",
      searchBreed: "",
      searchAge: "",
      searchWeight: "",
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    addNew() {
      this.petFromData = {};
      this.openModal = true;
    },
    handleEdit(item) {
      this.openModal = true;
      this.petFromData = item;
    },
    async handleOk() {
      this.confirmLoading = true;
      try {
        this.verification();
        const { id } = this.petFromData;
        await sleep(800);
        if (id) {
          const index = findIndex(this.petList, (l) => l.id === id);
          this.petList[index] = this.petFromData;
        } else {
          this.petList.unshift({ id: uuidv4(), ...this.petFromData });
        }
        message.success("新增成功");
        this.updateLo();
        this.openModal = false;
      } finally {
        this.confirmLoading = false;
      }
    },
    // onPageChange(page, pageSize) {
    //   this.pagination.current = page;
    //   this.pagination.pageSize = pageSize;
    //   this.getData();
    // },
    getData() {
      this.petList = JSON.parse(localStorage.getItem("petList")) || [];
    },
    deleteRecord(id) {
      const index = findIndex(this.petList, (l) => l.id === id);
      this.petList.splice(index, 1);
      this.updateLo();
    },
    setPetFromData({ type, value }) {
      this.petFromData[type] = value;
      console.log("setPetFromData", this.petFromData);
    },
    verification() {
      const { petName, petBreed, petAge, petWeight } = this.petFromData;
      if (!petName || !petBreed || !petAge || !petWeight) {
        message.error("请填写完整信息");
        throw new Error("请填写完整信息");
      }
    },
    updateLo() {
      localStorage.setItem("petList", JSON.stringify(this.petList));
    },
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    handleReset() {
      this.searchName = "";
      this.searchBreed = "";
      this.searchAge = "";
      this.searchWeight = "";
      this.isSearch = false;
      this.searchList = [];
    },
    handleSearch() {
      this.isSearch = true;
      this.searchList = this.petList.filter((i) => {
        if (this.searchName && i.petName.includes(this.searchName)) {
          return true;
        }
        if (this.searchBreed && i.petBreed.includes(this.searchBreed)) {
          return true;
        }
        if (this.searchAge && i.petAge.includes(this.searchAge)) {
          return true;
        }
        if (this.searchWeight && i.petWeight.includes(this.searchWeight)) {
          return true;
        }
        return false;
      });
    },
    handleDeed() {
      this.$message.info("功能开发中");
    },
    handleVaccinate() {
      this.$message.info("功能开发中");
    },
    onStatusTitleClick() {
      // this.$message.info("你点击了状态栏表头");
    },
    onChange() {
      // this.$message.info("表格状态改变了");
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  margin-bottom: 54px;
}
.fold {
  width: calc(100% - 216px);
  display: inline-block;
}
.operator {
  margin-bottom: 18px;
}
@media screen and (max-width: 900px) {
  .fold {
    width: 100%;
  }
}
.text_red {
  color: #ed6f6f !important;
}
</style>
